package pers.lx.crm.base.util;

import java.lang.reflect.Field;
import java.util.Objects;

/**
 * Created by lxl on 2017/2/14.
 */
public final class ReflectUtil {

    public static Field getFieldByFieldName(Object obj, String fieldName){
        Field field = null ;
        Class<?> clas = obj.getClass() ;
        for (;clas!= Object.class;clas=clas.getSuperclass()){
            try {
                return clas.getDeclaredField(fieldName) ;
            } catch (NoSuchFieldException e) {
                e.printStackTrace();
            }
        }
        return null ;
    }

    public static Object getFieldValueByFieldName(Object obj, String fieldName){
        Object result = null ;
        Field field = ReflectUtil.getFieldByFieldName(obj, fieldName) ;
        if( field != null ){
            field.setAccessible(true);
            try {
                result = field.get(obj) ;
            } catch (IllegalArgumentException e){
                e.printStackTrace();
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            }
        }
        return result ;
    }

    public static void setFieldValueByFieldName(Object obj,String fieldName,Object value){
        Field field = ReflectUtil.getFieldByFieldName(obj,fieldName) ;
        if( field != null ){
            field.setAccessible(true);
            try {
                field.set(obj,value);
            } catch (IllegalArgumentException e){
                e.printStackTrace();
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            }
        }
    }

}
